package gyb.rasa.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import gyb.rasa.common.handler.exceptionhandler.MyException;
import gyb.rasa.common.utils.JwtUtil;
import gyb.rasa.entity.RasaMsg;
import gyb.rasa.entity.RasaResponse;
import gyb.rasa.entity.User;
import gyb.rasa.entity.vo.ChatAIRequest;
import gyb.rasa.entity.vo.GPT35Request;
import gyb.rasa.entity.vo.GPT3Request;
import gyb.rasa.mapper.UserMapper;
import gyb.rasa.service.HotService;
import gyb.rasa.service.UserService;
import org.apache.tomcat.util.json.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 郜宇博
 * @since 2023-04-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private final HotService hotService;
    private final static String TOKEN = "76b1f5df27086011ee88cc86c647768a";
    private final static String NTS = "CTS202304191456_FLXBtrak_763178317";

    public UserServiceImpl(HotService hotService) {
        this.hotService = hotService;
    }

    /**
     * 注册
     *
     * @param user 用户信息
     */
    @Override
    public void register(User user) {
        //获取注册数据
        String username = user.getUsername();
        String password = user.getPassword();
        String email = user.getEmail();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)  || StringUtils.isEmpty(email)) {
            throw new MyException(20001, "注册失败，信息不完整");
        }
        //提高效率，只需要查询是否存在，不需要查出具体对象
        Integer countUserName = baseMapper.selectCount(new QueryWrapper<User>().eq("username", username));
        if (countUserName > 0) {
            throw new MyException(20001, "用户名已经注册");
        }
        Integer countEmail = baseMapper.selectCount(new QueryWrapper<User>().eq("email", email));
        if (countEmail > 0) {
            throw new MyException(20001, "邮箱已经注册");
        }
        //数据添加数据库中
        User registerUser = new User();
        registerUser.setUsername(username);
        registerUser.setPassword(password);
        registerUser.setEmail(email);
        baseMapper.insert(user);
    }

    /**
     * 登录
     *
     * @param user 用户信息
     * @return token
     */
    @Override
    public String login(User user) {
        String email = user.getEmail();
        String password = user.getPassword();
        //非空校验
        if (StringUtils.isEmpty(email)||StringUtils.isEmpty(password)){
            throw new MyException(20001,"邮箱或密码为空");
        }
        //判断用户名是否正确
        User loginUser = baseMapper.selectOne(new QueryWrapper<User>()
                .eq("email", email));
        if (loginUser == null){
            throw new MyException(20001,"邮箱未注册");
        }
        //判断密码
        if (!password.equals(loginUser.getPassword())){
            throw new MyException(20001,"密码错误");
        }
        String username = loginUser.getUsername();
        //登录成功
        return JwtUtil.getJwtToken(String.valueOf(loginUser.getUid()), username);
    }

    /**
     * 通过token获取用户信息
     *
     * @param request http请求
     * @return User对象
     */
    @Override
    public User getUserByToken(HttpServletRequest request) {
        //根据token获取到memberId
        String userId = JwtUtil.getMemberIdByJwtToken(request);
        //查询数据库
        return baseMapper.selectById(userId);
    }

    /**
     * 与rasa对话
     *
     * @param rasaMsg
     * @return
     */
    @Override
    public ArrayList<RasaResponse> rasaChat(RasaMsg rasaMsg) {

        String chatUrl = "http://localhost:5005/webhooks/rest/webhook";
        RestTemplate restTemplate = new RestTemplate();
        ArrayList<RasaResponse> rasaResponses = null;
        try {
            rasaResponses = restTemplate.postForObject(chatUrl, rasaMsg, ArrayList.class);
        } catch (RestClientException e) {
            throw new MyException(20001,"rasa服务器异常");

        }
        return rasaResponses;
    }
    @Override
    public ArrayList<Map<String,String>> rasaChat2(RasaMsg rasaMsg){
        String chatUrl = "http://localhost:5005/webhooks/rest/webhook";
        RestTemplate restTemplate = new RestTemplate();
        ArrayList<Map<String,String>>   rasaResponses = null;
        try {
            rasaResponses = restTemplate.postForObject(chatUrl, rasaMsg, ArrayList.class);
        } catch (RestClientException e) {
            //System.out.println(e.fillInStackTrace());
            throw new MyException(20001,"rasa服务器异常");

        }
        return rasaResponses;
    }

    /**
     * GPT35对话
     *
     * @param gpt35Request 请求
     * @return map
     */
    @Override
    public Map<String, Object> chatGpt35(GPT35Request gpt35Request) {
        String chatUrl = "https://api.openai.com/v1/chat/completions";
        RestTemplate restTemplate = new RestTemplate();
        //restTemplate.getInterceptors().add(new LoggingInterceptor());
        //restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("UTF-8")));

        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(500000);
        requestFactory.setReadTimeout(500000);
        restTemplate.setRequestFactory(requestFactory);
        //请求体
        Map<String,Object> request = new HashMap<>();
        request.put("model","text-davinci-003");
        ArrayList<Map<String, String>> messages = new ArrayList<>();
        //每条message
        HashMap<String, String> message = new HashMap<>();
        message.put("content",gpt35Request.getContent());
        message.put("role",gpt35Request.getRole());
        messages.add(message);
        request.put("messages",messages);
        request.put("temperature",gpt35Request.getTemperature());
        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization","Bearer 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");
        headers.set("Content-Type","application/json");
        HttpEntity<String> requestEntity = new HttpEntity<>(JSONUtil.toJsonStr(request),headers);
        Map map = restTemplate.postForObject(chatUrl, requestEntity, HashMap.class);
        return map;
    }

    /**
     * GPT3对话
     *
     * @param gpt3Request 请求
     * @return map
     */
    @Override
    public Map<String, Object> chatGpt3(GPT3Request gpt3Request) {
        String chatUrl = "https://www.kuaisou.com/api/requestGpt";
        RestTemplate restTemplate = new RestTemplate();
        //restTemplate.getInterceptors().add(new LoggingInterceptor());
        //restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("UTF-8")));

        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(5000);
        requestFactory.setReadTimeout(5000);
        restTemplate.setRequestFactory(requestFactory);

        Map<String,String> request = new HashMap<>();
        request.put("image","");
        request.put("keyword",gpt3Request.getKeyword());
        request.put("md","GPT-3");
        request.put("token",TOKEN);
        request.put("_nts",NTS);
        Map map = restTemplate.postForObject(chatUrl, request, Map.class);
        return map;
    }

    /**
     * ChatAI
     *
     * @param chatAIRequest 请求
     * @return map
     */
    @Override
    public Map<String, Object> ChatAI(ChatAIRequest chatAIRequest) {
        String chatUrl = "https://www.kuaisou.com/api/search";
        RestTemplate restTemplate = new RestTemplate();
        Map<String,String> request = new HashMap<>();
        request.put("keyword",chatAIRequest.getKeyword());
        request.put("token",TOKEN);
        Map map = restTemplate.postForObject(chatUrl, request, Map.class);
        return map;
    }

    /**
     * 获取所有user
     *
     * @param current 当前页
     * @param limit   最大数量
     * @return userList
     */
    @Override
    public IPage<User> getUserByPage(Long current, Long limit) {
        IPage<User> userPage = new Page<>(current,limit);
        IPage<User> page = this.page(userPage);
        return page;
    }

}
